package com.sheeran.aichat.utils.rest;

import com.sheeran.aichat.dto.common.rest.WrappedResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应返回
 *
 * @author: sheeran
 * @create: 2025/02/20
 */
@ControllerAdvice(annotations = WrappedResponseController.class)
public class WrappedResponseHandler implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (MediaType.APPLICATION_JSON.equals(selectedContentType)) {
            // 如果响应返回对象为统一响应体，则直接返回
            if (body instanceof WrappedResponse) {
                return body;
            }

            // 封装并返回
            return new WrappedResponse<>(ResponseCode.SUCCESS, body);
        }

        // 非JSON格式body直接跳过，包括String、文件、图片等
        return body;
    }
}
